package org.ntu.wkw.ip.controller;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class EnterChatroomServlet
 */
@WebServlet("/LeaveChatroomServlet")
public class LeaveChatroomServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LeaveChatroomServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String chatroom_id = request.getParameter("chatroom_id");
		ServletContext sc = request.getServletContext();
		String onlineUsersOfRoom = "onlineUsers_"+chatroom_id;
		if(sc.getAttribute(onlineUsersOfRoom)==null){
			sc.setAttribute(onlineUsersOfRoom, new ArrayList());
		}
		ArrayList onlineUserList = (ArrayList)sc.getAttribute(onlineUsersOfRoom);
		onlineUserList.remove(username);
		request.setAttribute("uname", username);
		request.setAttribute("chatroom_id", chatroom_id);
		request.getRequestDispatcher("Logout.jsp").forward(request, response);
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

}
